package com.example.multithread.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * @ClassName ConcurrentDemo
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2020/5/13 4:35 PM
 * @Version 1.0
 */
public class ConcurrentDemo {

	private final static Logger log = LoggerFactory.getLogger(ConcurrentDemo.class);

	public static void main(String[] args) throws InterruptedException {
		Map<Integer, Integer> hashMap = new HashMap<>(30000);
		Map<Integer, Integer> hashtable = new Hashtable<>();
		Map<Integer, Integer> synchronizedMap = Collections.synchronizedMap(new Hashtable<>());
		ConcurrentHashMap concurrentMap = new ConcurrentHashMap();
		ConcurrentNavigableMap<Integer, Integer> objectObjectConcurrentSkipListMap = new ConcurrentSkipListMap<>();
		ConcurrentSkipListSet<Integer> concurrentSkipListSet = new ConcurrentSkipListSet<>();
		ConcurrentLinkedDeque<Integer> concurrentLinkedDeque = new ConcurrentLinkedDeque<>();
		ConcurrentLinkedQueue<Integer> objectConcurrentLinkedQueue = new ConcurrentLinkedQueue<>();

		Thread t1 = new Thread(() -> IntStream.rangeClosed(1, 10000).forEach(i -> {
			hashMap.put(i, i);
			synchronizedMap.put(i, i);
			hashtable.put(i, i);
			concurrentMap.putIfAbsent(i, i);
			objectObjectConcurrentSkipListMap.put(i, i);
		}));

		Thread t2 = new Thread(() -> {
			IntStream.rangeClosed(10001, 20000).forEach(i -> {
				hashMap.put(i, i);
				hashtable.put(i, i);
				synchronizedMap.put(i, i);
				concurrentMap.putIfAbsent(i, i);
				objectObjectConcurrentSkipListMap.put(i, i);
			});
		});

		t1.start();
		t2.start();
		t2.join();
		t1.join();
		log.info("hashMap容量: {}", hashMap.size());//不安全, 不能用
		log.info("synchronizedMap容量: {}", synchronizedMap.size());//不安全, 不能用
		log.info("hashtable容量: {}", hashtable.size());
		log.info("concurrentMap容量: {}", concurrentMap.size());
		log.info("objectObjectConcurrentSkipListMap容量: {}", objectObjectConcurrentSkipListMap.size());
	}
}
